<?php
// +-------------------------------------------------------------------
// | 
// +-------------------------------------------------------------------
// | Copyright (c) 2009-2016 All rights reserved.
// +-------------------------------------------------------------------
namespace Kcdns\Admin\Model;

class CategoryModel extends CommonModel
{

    public function getTree ($id = 0, $field = true)
    {
        /* 获取当前分类信息 */
        if ($id)
        {
            $map = array();
            is_numeric($id) ? $map['id'] = $id : $map['name'] = $id;
            $info = $this->field($field)->where($map)->find();
            $id = $info['id'];
        }
        
        /* 获取所有分类 */
        $map = array(
                'status' => array(
                        'gt',
                        - 1
                )
        );
        $list = $this->field($field)->where($map)->order('sort')->select();
        $list = list_to_tree($list, $pk = 'id', $pid = 'pid', $child = '_', $root = $id);
        // 指定分类则返回当前分类极其子分类, 否则返回所有分类
        isset($info) ? $info['_'] = $list : $info = $list;
        return $info;
    }

    protected function _del ($delOptions)
    {
        $id = $delOptions['where']['id'];
        
        // 判断该分类下有没有子分类，有则不允许删除
        $child = $this->where(array(
                'pid' => $id
        ))->field('id')->select();
        if (! empty($child))
        {
            throw new \Exception('请先删除该分类下的子分类');
        }
        
        // 判断该分类下有没有内容
        $document_list = M('Document')->where(array(
                'category_id' => $id
        ))->field('id')->select();
        if (! empty($document_list))
        {
            throw new \Exception('请先删除该分类下的文章（包含回收站）');
        }
        return parent::_del($delOptions);
    }

    /**
     * 查询后解析扩展信息
     *
     * @param array $data
     *            分类数据
     * @author 麦当苗儿 <zuojiazi@vip.qq.com>
     */
    protected function _after_find (&$data, $options)
    {
        /* 分割模型 */
        if (! empty($data['model']))
        {
            $data['model'] = explode(',', $data['model']);
        }
        
        if (! empty($data['model_sub']))
        {
            $data['model_sub'] = explode(',', $data['model_sub']);
        }
        
        /* 分割文档类型 */
        if (! empty($data['type']))
        {
            $data['type'] = explode(',', $data['type']);
        }
        
        /* 分割模型 */
        if (! empty($data['reply_model']))
        {
            $data['reply_model'] = explode(',', $data['reply_model']);
        }
        
        /* 分割文档类型 */
        if (! empty($data['reply_type']))
        {
            $data['reply_type'] = explode(',', $data['reply_type']);
        }
        
        /* 还原扩展数据 */
        if (! empty($data['extend']))
        {
            $data['extend'] = json_decode($data['extend'], true);
        }
    }
}
